<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 裕优昌
 */
class YuyouchangController extends PayController{
    protected $config;
    protected $class;

    // 公钥证书
    protected $public = 'Files/Yuyouchang/bbb.cer';
    // 签名证书
    protected $private= 'Files/Yuyouchang/aaa.pfx';
    // 签名密码
    protected $pwd = 'qaz123';
    protected $apiurl = 'https://cashier.hefupal.com/paygate/v1/smpay';

    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){

        //echo '<pre/>'; print_r($_SERVER); EXIT;
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merchantNo'] = $this->config['mch_id'];
        $data['version'] = 'v1';
        $data['channelNo'] = '05';
        $data['tranCode'] = 'YS1003';
        $data['tranFlow'] = $return['orderid'];
        $data['tranDate'] = date("Ymd",time());
        $data['tranTime'] = date("His",time());
        $data['amount'] = $return['amount']*100;
        $data['currency'] = 'CNY';
        $data['payType'] = '15';
        $data['notifyUrl'] = $return['notifyurl'];
        $data['bizType'] = '01';
        $data['goodsName'] = 'zf';

        $data['buyerName'] = $this->encryptData("wanglianfu", $this->public); //加密
        $data['buyerId'] = 'wanglianfu';
        $data['valid'] = '5';
        $data['remark'] = 'zf';
        $data['YUL1'] = $return['callbackurl'];
        switch(agentType()){
            case 'pc':
                $data['YUL2'] = 'WAP';
                break;
            case 'ios':
                $data['YUL2'] = 'IOS';
                break;
            default:
                $data['YUL2'] = 'ANDROID';
        }
        $data['YUL3'] = getIP();

        ksort($data);
        $this->sign($data);

        $result = $this->post ( $data, $this->apiurl );
        $resultData = $this->convertStringToArray($result);
        $res = $this->verifys($resultData);

        if(!$res){
            $this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        parse_str($res,$res);
        //echo '<pre/>'; var_dump($res); exit;

        $code = $res['qrCodeURL'];
        if(!$code || $code ==='null'){
            if($res['rtnMsg']){
                $this->showmessage($res['rtnMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if(isMobile()){
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            //支付宝
            case 17:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 18:
                $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    function verifys($params) {
        // 公钥
        $public_key = $this->getPublicKey ($this->public);
        // 签名串
        $sign_str = $params ['sign'];
        $sign_str=str_replace(" ","+",$sign_str);
        unset ( $params ['sign'] );
        $params_str = httpstr($params);

        $sign = base64_decode ( $sign_str );
        $isSuccess = openssl_verify ( $params_str, $sign, $public_key);

        if($isSuccess=='1'){
            return $params_str;
        }else{
            //echo $params_str.'&sign='.$sign_str.'&msg=验签失败' . '<br/><br/>';  exit;
            return false;
        }
    }

    function convertStringToArray($str) {
        $result = array ();

        if (! empty ( $str )) {
            $temp = preg_split ( '/&/', $str );
            if (! empty ( $temp )) {
                foreach ( $temp as $key => $val ) {
                    $arr = preg_split ( '/=/', $val, 2 );
                    if (! empty ( $arr )) {
                        $k = $arr ['0'];
                        $v = $arr ['1'];
                        $result [$k] = $v;
                    }
                }
            }
        }
        return $result;
    }


    function post($params, $url) {
        $opts = httpstr($params);
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false ); // 不验证证书
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false ); // 不验证HOST
        //curl_setopt ( $ch, CURLOPT_SSLVERSION, 3 );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
            'Content-type:application/x-www-form-urlencoded;charset=UTF-8'
        ) );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $opts );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $html = curl_exec ( $ch );
        if(curl_errno($ch)){
            $errmsg = curl_error($ch);
            curl_close ( $ch );
            $this->showmessage($errmsg,['code'=>C("THIRDCODES.".$this->class)]);
        }
        if( curl_getinfo($ch, CURLINFO_HTTP_CODE) != "200"){
            $errmsg = curl_error($ch);
            curl_close ( $ch );
            $this->showmessage($errmsg,['code'=>C("THIRDCODES.".$this->class)]);
        }
        curl_close ( $ch );
        return $html;
    }

    private function sign(&$params) {
        if(isset($params['sign'])){
            unset($params['sign']);
        }
        // 转换成key=val&串
        $params_str = httpstr($params);

        // 签名证书路径
        $cert_path = $this->private;

        $private_key = $this->getPrivateKey ( $cert_path );
        // 签名
        $sign_falg = openssl_sign ( $params_str, $sign, $private_key, OPENSSL_ALGO_SHA1 );
        if ($sign_falg) {
            $sign_base64 = base64_encode ( $sign );
            $params ['sign'] = $sign_base64;
        }else{
            $this->showmessage('签名失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }
    }

    public function encryptData($data, $cert_path) {
        $public_key = $this->getPublicKey ( $cert_path );
        openssl_public_encrypt ( $data, $crypted, $public_key);
        return base64_encode ( $crypted );
    }

    function getPublicKey($cert_path) {
        return file_get_contents ( $cert_path );
    }

    function getPrivateKey($cert_path) {
        $pkcs12 = file_get_contents ( $cert_path );
        openssl_pkcs12_read ( $pkcs12, $certs, $this->pwd );
        return $certs ['pkey'];
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = I("post.");

        /*$p = array (
            'YUL1' => '',
            'YUL2' => '',
            'YUL3' => '',
            'amount' => '1000',
            'channelNo' => '05',
            'ext1' => '',
            'ext2' => '',
            'merchantNo' => 'S20170907011890',
            'paySerialNo' => '8120412102448366624768',
            'remark' => 'zf',
            'rtnCode' => '0000',
            'rtnMsg' => '交易成功',
            'settDate' => '20181204',
            'sign' => 'NX6LyCtKZitg7UwASmXCpt6A3IlBivYTY9Ls8TRH2RjjmSww87JwcZmFsCG7PZQZv6dairxdKtMki1m+2OzDNtMilBxRD7OKAb4a7GQ7WwxQJIxJ/UZwuJl9Oc/gLdva+bLcEXM73IYk29UsHo5BO9WfRwUqaz8j8rQXmcd2IMM=',
            'tranCode' => 'YS1003',
            'tranFlow' => '2018120416255393812',
            'version' => 'v1',
        );*/

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['tranFlow'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> httpstr($p),
            "pay_orderid_rd"=>$p['paySerialNo']
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        //$sign = $p['sign'];
        //unset($p['sign']);

        ksort($p);

        $flag = $this->verifys($p);

        //echo '<pre/>';var_dump($flag); exit;


        if($p['rtnCode'] !== '0000'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'YYYYYY');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}